package Campus.help.task.Interceptor;

import Campus.help.common.config.MyThreadLocal;
import Campus.help.common.utils.JwtUtil;
import Campus.help.common.vo.UserInfoVo;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    private static final String prefixName = "User:Login:";
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private MyThreadLocal threadLocal;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入拦截器.......");
        Map<String, Object> map = new HashMap<>();

        //获取请求头中的令牌
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            map.put("code",4040);
            map.put("msg","为携带token");
            return false;
        }
        try {
            //验证令牌
            Claims jwt = JwtUtil.parseJWT(token);
            String id = jwt.getId();
            String userName = jwt.getSubject();
            UserInfoVo userInfo = (UserInfoVo)redisTemplate.opsForValue().get(prefixName + userName);
            if (Objects.isNull(userInfo)){
                map.put("code",4000);
                map.put("msg","用户未登录");
                return false;
            }
            threadLocal.set(userInfo);
            return true;
        } catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("code",4020);
            map.put("msg","无效签名");
        } catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("code",4030);
            map.put("msg","token过期");

        } catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","token算法不一致");
        } catch (Exception e){
            e.printStackTrace();
            map.put("code",4010);
            map.put("msg","token无效");
        }
        map.put("state","flase");

        //将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);

        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
        log.info("threadLocal remove");
    }
}